import React, { useState, useEffect } from 'react';
import { Dialog, Button, Card, Message, Tab } from '@alifd/next';
import { IPublicModelPluginContext } from '@alilc/lowcode-types';
import { getCustomComponents, deleteCustomComponent } from '../utils/storage';
import { CustomComponent } from '../types';
import ComponentPreview from './ComponentPreview';

interface ViewDialogProps {
  ctx: IPublicModelPluginContext;
}

const ViewDialog: React.FC<ViewDialogProps> = ({ ctx }) => {
  const [components, setComponents] = useState<CustomComponent[]>([]);

  // 加载组件列表
  useEffect(() => {
    loadComponents();

    // 监听自定义组件刷新事件
    const { event } = ctx;
    const handleRefresh = () => {
      loadComponents();
    };

    event.on('customComponent:refresh', handleRefresh);

    // 清理函数：组件卸载时移除监听器
    return () => {
      event.off('customComponent:refresh', handleRefresh);
    };
  }, []);

  const loadComponents = () => {
    const data = getCustomComponents();
    setComponents(data);
  };

  const handleDelete = (id: string, title: string) => {
    Dialog.confirm({
      title: '确认删除',
      content: `确定要删除组件 "${title}" 吗？`,
      onOk: () => {
        deleteCustomComponent(id);
        Message.success('删除成功');
        loadComponents();
      },
    });
  };

  // 应用组件到画布
  const handleApply = (component: CustomComponent) => {
    console.log('应用自定义组件:', component);
    console.log('组件 Schema:', component.schema);

    try {
      // 获取当前项目
      const { project } = ctx;
      const currentDocument = project.currentDocument;

      if (!currentDocument) {
        throw new Error('没有找到当前文档');
      }

      // 获取当前选中的节点
      const selection = currentDocument.selection;
      const selectedNode = selection.getTopNodes()?.[0];

      let applyMode = 'replace'; // 默认替换整个页面
      let targetNode = null;

      // 检查是否有选中的节点
      if (selectedNode) {
        console.log('🎯 检测到选中的节点:', {
          id: selectedNode.id,
          componentName: selectedNode.componentName,
          isContainer: selectedNode.isContainer,
        });

        // 判断选中的节点是否是容器（可以包含子节点）
        if (selectedNode.isContainer) {
          applyMode = 'append'; // 添加到容器
          targetNode = selectedNode;
          console.log('✅ 选中节点是容器，将组件添加到容器中');
        } else {
          console.log('⚠️ 选中节点不是容器，将替换整个页面');
        }
      } else {
        console.log('ℹ️ 没有选中节点，将替换整个页面');
      }

      if (applyMode === 'append' && targetNode) {
        // 模式1: 添加到选中的容器
        console.log('开始将组件添加到选中容器...');

        // 获取组件的子节点（如果组件本身是 Page，取其 children）
        let nodesToAdd = [];
        if (component.schema.componentName === 'Page' && component.schema.children) {
          // 组件是完整页面，取其子节点
          nodesToAdd = component.schema.children;
        } else {
          // 组件本身就是组件，直接添加
          nodesToAdd = [component.schema];
        }

        console.log('准备添加的节点:', nodesToAdd);

        // 使用 importSchema 方法添加节点到容器
        if (targetNode.children) {
          targetNode.children.importSchema(nodesToAdd);
          console.log('✅ 成功调用 importSchema');
          Message.success(`已成功将组件添加到容器：${targetNode.componentName}`);
        } else {
          throw new Error('选中的容器没有 children 属性');
        }

        console.log('✅ 组件已添加到容器');
      } else {
        // 模式2: 替换整个页面 Schema
        console.log('开始应用组件到页面...');

        // 确保根组件是 Page、Block 或 Component
        let schemaToApply = component.schema;
        const validRootComponents = ['Page', 'Block', 'Component'];

        if (validRootComponents.indexOf(component.schema.componentName) === -1) {
          // 如果不是有效的根组件，包装在 Page 中
          console.log('⚠️ 组件不是有效的根组件，包装在 Page 中');
          schemaToApply = {
            componentName: 'Page',
            id: 'page_' + Date.now(),
            props: {},
            children: [component.schema],
          } as any;
        }

        // 导入新的 schema（会替换当前页面）
        project.importSchema({
          componentsTree: [schemaToApply],
        } as any);

        Message.success(`已成功应用组件：${component.title}`);
        console.log('✅ 组件应用成功');
      }

      // 应用成功后刷新组件列表
      loadComponents();
    } catch (error) {
      console.error('❌ 应用组件失败:', error);
      Message.error(`应用组件失败：${error}`);
    }
  };

  const handlePreview = (component: CustomComponent) => {
    Dialog.alert({
      title: `组件预览：${component.title}`,
      content: (
        <div>
          <div style={{ marginBottom: '16px' }}>
            <div style={{ marginBottom: '8px' }}>
              <strong>组件名称：</strong> {component.componentName}
            </div>
            <div style={{ marginBottom: '8px' }}>
              <strong>描述：</strong> {component.description || '无'}
            </div>
            <div style={{ marginBottom: '8px' }}>
              <strong>创建时间：</strong> {new Date(component.createTime).toLocaleString()}
            </div>
          </div>

          <Tab>
            <Tab.Item title="可视化预览" key="preview">
              <div style={{ padding: '16px 0' }}>
                <div style={{ marginBottom: '8px' }}>
                  <strong>组件预览：</strong>
                </div>
                <ComponentPreview
                  schema={component.schema}
                  scale={0.5}
                  height={500}
                />
              </div>
            </Tab.Item>
            <Tab.Item title="Schema 代码" key="schema">
              <div style={{ padding: '16px 0' }}>
                <div style={{ marginBottom: '8px' }}>
                  <strong>Schema：</strong>
                </div>
                <pre style={{
                  background: '#f5f5f5',
                  padding: '12px',
                  borderRadius: '4px',
                  maxHeight: '400px',
                  overflow: 'auto',
                  fontSize: '12px',
                }}>
                  {JSON.stringify(component.schema, null, 5)}
                </pre>
              </div>
            </Tab.Item>
          </Tab>
        </div>
      ),
      style: { width: '800px' },
    });
  };

  return (
    <div style={{ padding: '16px', height: '100%', overflow: 'auto' }}>
      {components.length === 0 ? (
        <div style={{ textAlign: 'center', padding: '40px', color: '#999' }}>
          暂无自定义组件，请先封装组件
        </div>
      ) : (
        <div style={{ display: 'flex', flexDirection: 'column', gap: '16px' }}>
          {components.map((component) => (
            <Card
              key={component.id}
              title={component.title}
              extra={
                <Button
                  type="secondary"
                  size="small"
                  warning
                  onClick={() => handleDelete(component.id, component.title)}
                >
                  删除
                </Button>
              }
            >
              <div style={{ marginBottom: '12px' }}>
                <ComponentPreview
                  schema={component.schema}
                  scale={0.25}
                  height={150}
                />
              </div>

              <div style={{ marginBottom: '8px' }}>
                <strong>组件名称：</strong>{component.componentName}
              </div>
              <div style={{ marginBottom: '12px', color: '#666', fontSize: '12px' }}>
                {component.description || '暂无描述'}
              </div>
              <div style={{ marginBottom: '12px', fontSize: '12px', color: '#999' }}>
                创建时间：{new Date(component.createTime).toLocaleString()}
              </div>
              <div style={{ display: 'flex', gap: '8px' }}>
                <Button
                  type="primary"
                  size="small"
                  onClick={() => handleApply(component)}
                  style={{ flex: 1 }}
                >
                  应用
                </Button>
                <Button
                  type="normal"
                  size="small"
                  onClick={() => handlePreview(component)}
                  style={{ flex: 1 }}
                >
                  查看详情
                </Button>
              </div>
            </Card>
          ))}
        </div>
      )}
    </div>
  );
};

export default ViewDialog;
